from rest_framework import status, mixins
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from .services import ComplaintService
from .serializers import ComplaintSerializer, CreateComplaintSerializer, UpdateComplaintSerializer


class ComplaintViewSet(mixins.ListModelMixin,
                      mixins.CreateModelMixin,
                      mixins.RetrieveModelMixin,
                      mixins.DestroyModelMixin,
                      GenericViewSet):
    """投诉视图集"""
    permission_classes = [IsAuthenticated]
    serializer_class = ComplaintSerializer
    
    def get_queryset(self):
        """根据用户角色返回不同的投诉查询集"""
        try:
            return ComplaintService.get_complaints_for_user(self.request.user)
        except PermissionError:
            return []
    
    def get_serializer_class(self):
        """根据操作返回不同的序列化器"""
        if self.action == 'create':
            return CreateComplaintSerializer
        elif self.action in ['update', 'partial_update']:
            return UpdateComplaintSerializer
        return ComplaintSerializer
    
    def list(self, request, *args, **kwargs):
        """获取投诉列表"""
        try:
            complaints = ComplaintService.get_complaints_for_user(request.user)
            serializer = self.get_serializer(complaints, many=True)
            return Response(serializer.data)
        except PermissionError as e:
            return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)
    
    def create(self, request, *args, **kwargs):
        """创建投诉"""
        serializer = self.get_serializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            try:
                complaint = ComplaintService.create_complaint(serializer.validated_data, request.user)
                return Response(ComplaintSerializer(complaint).data, status=status.HTTP_201_CREATED)
            except PermissionError as e:
                return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)
            except ValueError as e:
                return Response({'error': str(e)}, status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    def retrieve(self, request, *args, **kwargs):
        """获取投诉详情"""
        complaint_id = kwargs.get('pk')
        try:
            complaint = ComplaintService.get_complaint_detail(complaint_id, request.user)
            serializer = ComplaintSerializer(complaint)
            return Response(serializer.data)
        except ValueError as e:
            return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)
        except PermissionError as e:
            return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)
    
    def update(self, request, *args, **kwargs):
        """更新投诉（处理投诉）"""
        complaint_id = kwargs.get('pk')
        try:
            complaint = ComplaintService.update_complaint(complaint_id, request.data, request.user)
            return Response(ComplaintSerializer(complaint).data)
        except ValueError as e:
            return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)
        except PermissionError as e:
            return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)
    
    def destroy(self, request, *args, **kwargs):
        """删除投诉"""
        complaint_id = kwargs.get('pk')
        try:
            ComplaintService.delete_complaint(complaint_id, request.user)
            return Response({'message': '投诉已删除'}, status=status.HTTP_204_NO_CONTENT)
        except ValueError as e:
            return Response({'error': str(e)}, status=status.HTTP_404_NOT_FOUND)
        except PermissionError as e:
            return Response({'error': str(e)}, status=status.HTTP_403_FORBIDDEN)
    
    @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated])
    def upload_evidence(self, request):
        """上传投诉证据图片"""
        try:
            from common.utils import upload_to_minio
            image_file = request.FILES.get('image')
            if image_file:
                # 上传到MinIO
                image_url = upload_to_minio(
                    image_file, 
                    request.user.id, 
                    'complaint_evidence'
                )
                
                return Response({'url': image_url}, status=status.HTTP_201_CREATED)
            else:
                return Response({'error': '未提供图片文件'}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({'error': f'上传失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
